package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.GroupChatRequestMessage;
import host.skiree.nettydemo.message.GroupChatResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.impl.RoomChannelImpl;
import host.skiree.nettydemo.server.dto.impl.UserChannelImpl;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.ChannelHandlerContext;

import java.util.Set;

/**
 * @author gcl
 * @date 2022/9/21 8:36
 */
public class GroupChat implements MessageHandler {
    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        GroupChatRequestMessage groupChatRequestMessage = (GroupChatRequestMessage) message;
        String groupName = groupChatRequestMessage.getGroupName();
        String userName = groupChatRequestMessage.getFrom();
        String text = groupChatRequestMessage.getContent();
        if (RoomChannelImpl.ROOM_CHANNEL_MAP.get(groupName) != null){
            Set<String> names = RoomChannelImpl.ROOM_CHANNEL_MAP.get(groupName);
            UserChannelImpl.USER_CHANNEL_MAP.forEach( (k, v) -> {
                if ( names.contains(v) && !v.equals(userName) ){
                    k.writeAndFlush(new GroupChatResponseMessage( groupName + " : "+ userName, text));
                }
            } );
        }else {
            ctx.writeAndFlush(new GroupChatResponseMessage(false,"该聊天室不存在"));
        }
    }
}
